package zhongbo.java.air.monitor.task;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import zhongbo.java.air.monitor.mapper.FlightActivityDailyMapper;
import zhongbo.java.air.monitor.model.FlightActivityDaily;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class AircraftActivityTask {

    @Autowired
    private FlightActivityDailyMapper flightActivityDailyMapper;

    // 调整为每10分钟执行
    @Scheduled(
            fixedDelay = 1 * 60 * 100
            , initialDelay = 5000
    )
    @Transactional
    public void updateDailyActivity() {
        log.info("---- 开始执行每日活动飞机统计任务 -----");
        try {
            doJob();
            log.info("---- 每日活动飞机统计任务执行完成 -----");
        } catch (Exception e) {
            log.error("执行每日活动飞机统计任务时发生异常", e);
        }
    }

    private void doJob() {
        String today = DateUtil.formatDate(new Date());
        // 1. 从轨迹表查询当天出现过的ICAO码
        List<FlightActivityDaily> activeICaos = flightActivityDailyMapper.selectDailyStats(today);
        log.info("查询结果: {}条", activeICaos.size());

        // 2. 批量插入或更新
        for (FlightActivityDaily activity : activeICaos) {
            // 根据 icaoCode 和 date 查询是否已存在记录
            List<FlightActivityDaily> existingRecords = flightActivityDailyMapper.selectByIcaoAndDate(activity.getIcaoCode(), activity.getDate());
            if (existingRecords != null && !existingRecords.isEmpty()) {
                FlightActivityDaily existingRecord = existingRecords.get(0);
                log.info("更新记录: icaoCode={}, date={}", activity.getIcaoCode(), activity.getDate());

                // 更新记录
                activity.setId(existingRecord.getId());
                // 更新其他字段
                activity.setFirstSeenTime(existingRecord.getFirstSeenTime());
                activity.setLastSeenTime(existingRecord.getLastSeenTime());
                activity.setLastLatitude(existingRecord.getLastLatitude());
                activity.setLastLongitude(existingRecord.getLastLongitude());
                activity.setLastAltitude(existingRecord.getLastAltitude());
                activity.setLastSpeed(existingRecord.getLastSpeed());
                activity.setLastHeading(existingRecord.getLastHeading());
                activity.setOccurrenceCount(existingRecord.getOccurrenceCount());
                // 补充飞机字典表字段
                FlightActivityDaily aircraftInfo = flightActivityDailyMapper.selectAircraftInfoByIcao(activity.getIcaoCode());
                if (aircraftInfo != null) {
                    activity.setRegistration(aircraftInfo.getRegistration());
                    activity.setAirline(aircraftInfo.getAirline());
                    activity.setAircraftType(aircraftInfo.getAircraftType());
                } else {
                    // 如果飞机字典表没有相关信息，设置默认值
                    activity.setRegistration("UNKNOWN");
                    activity.setAirline("UNKNOWN");
                    activity.setAircraftType("UNKNOWN");
                }
                // 设置 updatedTime 字段为当前时间，确保包含毫秒数
                activity.setUpdatedTime(new Date());
                flightActivityDailyMapper.updateById(activity);
            } else {
                // 新增记录
                // 补充飞机字典表字段
                FlightActivityDaily aircraftInfo = flightActivityDailyMapper.selectAircraftInfoByIcao(activity.getIcaoCode());
                if (aircraftInfo != null) {
                    activity.setRegistration(aircraftInfo.getRegistration());
                    activity.setAirline(aircraftInfo.getAirline());
                    activity.setAircraftType(aircraftInfo.getAircraftType());
                } else {
                    // 如果飞机字典表没有相关信息，设置默认值
                    activity.setRegistration("UNKNOWN");
                    activity.setAirline("UNKNOWN");
                    activity.setAircraftType("UNKNOWN");
                }
                // 设置 date 字段为当天的日期
                activity.setDate(DateUtil.parseDate(today));
                // 设置 createdTime 和 updatedTime 字段为当前时间，确保包含毫秒数
                Date now = new Date();
                activity.setCreatedTime(now);
                activity.setUpdatedTime(now);
                // 先查询是否存在记录
                List<FlightActivityDaily> existingRecordsBeforeInsert = flightActivityDailyMapper.selectByIcaoAndDate(activity.getIcaoCode(), activity.getDate());
                if (existingRecordsBeforeInsert != null && !existingRecordsBeforeInsert.isEmpty()) {
                    FlightActivityDaily existingRecordBeforeInsert = existingRecordsBeforeInsert.get(0);
                    // 更新记录
                    activity.setId(existingRecordBeforeInsert.getId());
                    // 更新其他字段
                    activity.setFirstSeenTime(existingRecordBeforeInsert.getFirstSeenTime());
                    activity.setLastSeenTime(existingRecordBeforeInsert.getLastSeenTime());
                    activity.setLastLatitude(existingRecordBeforeInsert.getLastLatitude());
                    activity.setLastLongitude(existingRecordBeforeInsert.getLastLongitude());
                    activity.setLastAltitude(existingRecordBeforeInsert.getLastAltitude());
                    activity.setLastSpeed(existingRecordBeforeInsert.getLastSpeed());
                    activity.setLastHeading(existingRecordBeforeInsert.getLastHeading());
                    activity.setOccurrenceCount(existingRecordBeforeInsert.getOccurrenceCount());
                    // 补充飞机字典表字段
                    if (aircraftInfo != null) {
                        activity.setRegistration(aircraftInfo.getRegistration());
                        activity.setAirline(aircraftInfo.getAirline());
                        activity.setAircraftType(aircraftInfo.getAircraftType());
                    } else {
                        // 如果飞机字典表没有相关信息，设置默认值
                        activity.setRegistration("UNKNOWN");
                        activity.setAirline("UNKNOWN");
                        activity.setAircraftType("UNKNOWN");
                    }
                    // 设置 updatedTime 字段为当前时间，确保包含毫秒数
                    activity.setUpdatedTime(new Date());
                    flightActivityDailyMapper.updateById(activity);
                } else {
                    // 插入新记录
                    flightActivityDailyMapper.insert(activity);
                }
            }
        }
    }


}